package com.cx.mall.demo.controller;

import com.cx.mall.common.utils.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test/mq")
public class MQController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    StreamBridge streamBridge;
    @GetMapping("/send")
    public ResponseVO send(@RequestParam String msg){
        streamBridge.send("testOutput-out-0",msg);
        return ResponseVO.success("发送成功");
    }

    @GetMapping("/payload")
    public ResponseVO payLoad(@RequestParam String msg){
        Message<?> message = MessageBuilder.withPayload(msg)
                .setHeader("TAG", "success") // 定义消息头传递 Tag
                .build();
        streamBridge.send("testOutput-out-0", message);
        return ResponseVO.success("发送成功");
    }

    @GetMapping("/delay")
    public ResponseVO delay(@RequestParam String msg){
        Message<?> message = MessageBuilder.withPayload(msg)
                .setHeader("DELAY", 3)//0-0,1-1,2-5,3-10,4-30,5-60,6-120,7-180,8-240,9-300...
                .setHeader("TAG", "delay")
                .build();
        streamBridge.send("testOutput-out-0", message);
        return ResponseVO.success("发送成功");
    }

    @GetMapping("/order")
    public ResponseVO order(String msg,String orderId){
        Message<?> message = MessageBuilder.withPayload(msg)
                // 同一个订单号数据进行同一个队列
                .setHeader("ORDERLY_KEY", orderId)
                .build();
        streamBridge.send("testOutput-out-0", message);
        return ResponseVO.success("发送成功");
    }

    @GetMapping("/unique")
    public ResponseVO unique(String msg,String key){
        Message<?> message = MessageBuilder.withPayload(msg).build();
        // 必须设置合理过期时间,未设置过期时间导致锁无法自动释放(如系统崩溃)
        if(redisTemplate.opsForValue().setIfAbsent("REQ_" + key,"1",10, TimeUnit.SECONDS)){
            streamBridge.send("test3Output-out-0", message);
        }
        return ResponseVO.success("发送成功");
    }


}
